/**
 * 
 */
package com.magus.project.yddemo.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.magus.framework.core.persistence.JpaSearchUtils;
import com.magus.framework.core.persistence.SearchFilter;
import com.magus.framework.core.repository.BaseRepository;
import com.magus.framework.core.service.BaseService;
import com.magus.framework.system.entity.Company;
import com.magus.project.yddemo.entity.BenchmarkValue;
import com.magus.project.yddemo.entity.Indicator;
import com.magus.project.yddemo.entity.IndicatorData;
import com.magus.project.yddemo.entity.IndicatorDetail;
import com.magus.project.yddemo.repository.BenchmarkValueRepository;
import com.magus.project.yddemo.vobean.BenchamarkSurroundVoBean;
import com.magus.project.yddemo.vobean.BenchmarkUnitValueVoBean;
import com.magus.project.yddemo.vobean.BenchmarkUnitVoBean;
import com.magus.sis.common.entity.ComUnit;

/**
 * @author wenyu.han
 * @date 2018-01-23 23:17:35
 */
@Service
@Transactional(readOnly = true)
public class BenchmarkValueService  extends BaseService<BenchmarkValue, String> {

	@Autowired
	private BenchmarkValueRepository benchmarkValueRepository;
	
	@Autowired
	private IndicatorDetailService detailService;
	
	@Autowired
	private IndicatorDataService dataService;
	
	@Autowired
	private BenchmarkValueService benchmarkService;
	
	@Override
	protected BaseRepository<BenchmarkValue, String> getBaseRepository() {
		return benchmarkValueRepository;
	}
	
	public List<BenchmarkUnitVoBean> findIndicators(List<Indicator> indicatorList,Date beginTime,Date endTime,String packageIds,String dimension) {
		List<String> packageIdList = Arrays.asList(packageIds.split(","));
		//1.查询指标Id对应指标的详细数据
		List<SearchFilter> searchFilters = new ArrayList<>();
		searchFilters.add(SearchFilter.in("indicator", indicatorList));
		searchFilters.add(SearchFilter.in("indicatorPackage.id", packageIdList));
		Specification<IndicatorDetail> detailSpec = JpaSearchUtils.buildAndSpec(searchFilters);
		List<IndicatorDetail> detailList = detailService.findAll(detailSpec);
		
		//2.根据detailList列表获取公司的个数
		List<Company> companyList = new ArrayList<>();
		detailList.forEach(detail ->{
			List<Company> list = companyList.stream().filter(company ->company.getId().equals(detail.getCompany().getId())).collect(Collectors.toList());
			if(list.size()==0){
				companyList.add(detail.getCompany());
			}
		});
		
		//3.根据dtailList列表获取机组的个数
		List<ComUnit> unitList = new ArrayList<>();
		detailList.forEach(detail ->{
			List<ComUnit> list = unitList.stream().filter(unit ->unit.getId().equals(detail.getComUnit().getId())).collect(Collectors.toList());
			if(list.size()==0){
				unitList.add(detail.getComUnit());
			}
		});
		
		//4.将公司、机组对应的指标数据进行整合
		List<BenchmarkUnitValueVoBean> benchmarkUnitValueVoBeanList = new ArrayList<>();
		detailList.forEach(detail -> {
			BenchmarkUnitValueVoBean vobean = new BenchmarkUnitValueVoBean();
			vobean.setIndicatorId(detail.getIndicator().getId());
			vobean.setCompanyId(detail.getCompany().getId());
			vobean.setCompanyName(detail.getCompany().getName());
			vobean.setUnitId(detail.getComUnit().getId());
			vobean.setUnitName(detail.getComUnit().getName());
			//查询实际值
			List<SearchFilter> searchs = new ArrayList<>();
			searchs.add(SearchFilter.equal("indicatorDetail.id", detail.getId()));
			searchs.add(SearchFilter.equal("dimension", dimension));
			searchs.add(SearchFilter.ge("time", beginTime.getTime()));
			searchs.add(SearchFilter.lt("time", endTime.getTime()));
			Specification<IndicatorData> dataSpec = JpaSearchUtils.buildAndSpec(searchs);
			IndicatorData data = dataService.findOne(dataSpec);
			if(data!=null){
				vobean.setData(data.getValue());
			}else{
				vobean.setData(null);
			}
			
			//查询设计值
			searchs = new ArrayList<>();
			searchs.add(SearchFilter.equal("indicatorDetail.id",  detail.getId()));
			searchs.add(SearchFilter.equal("indicatorDetail.indicatorPackage.dimension",  detail.getId()));
			Specification<BenchmarkValue> benchmarkSpec = JpaSearchUtils.buildAndSpec(searchs);
			BenchmarkValue benchmarkValue = benchmarkService.findOne(benchmarkSpec);
			if(benchmarkValue!=null){
				vobean.setDesignValue(benchmarkValue.getDesignValue());
			}else{
				vobean.setDesignValue(null);
			}
			benchmarkUnitValueVoBeanList.add(vobean);
		});
		
		//5.整理需要展示的列数
		List<BenchmarkUnitValueVoBean> indicatorByCompanyList = new ArrayList<>();
		String companyAndUnit = "";
		for(BenchmarkUnitValueVoBean benchmark : benchmarkUnitValueVoBeanList){
			String str = benchmark.getCompanyId()+benchmark.getUnitId();
			if(companyAndUnit.indexOf(str)<0){
				companyAndUnit += str + ",";
				indicatorByCompanyList.add(benchmark);
			}
		};
		
		//6.将指标和对应的公司机组数据整合
		List<BenchmarkUnitVoBean> benchmarkUnitVoBeanList = new ArrayList<>();
		indicatorList.forEach(indicator ->{
			BenchmarkUnitVoBean vobean = new BenchmarkUnitVoBean();
			vobean.setIndicatorByCompanyList(indicatorByCompanyList);
			vobean.setIndicatorName(indicator.getName());
			vobean.setCode(indicator.getCode());
			HashMap<String, BenchmarkUnitValueVoBean> beanMap = new HashMap<>();
			for (BenchmarkUnitValueVoBean ibc : indicatorByCompanyList) {
				String temp = "";
				for (BenchmarkUnitValueVoBean bkv : benchmarkUnitValueVoBeanList) {
					if (indicator.getId().equals(bkv.getIndicatorId())
							&&ibc.getCompanyId().equals(bkv.getCompanyId())
							&&ibc.getUnitId().equals(bkv.getUnitId())) {
						temp += ibc + ",";
						beanMap.put(bkv.getCompanyId()+bkv.getUnitId(), bkv);
					}
				}
				if (temp == "") {
					beanMap.put(ibc.getCompanyId()+ibc.getUnitId(), new BenchmarkUnitValueVoBean());
				}
			}
			vobean.setBenchmarkUnitBean(beanMap);
			benchmarkUnitVoBeanList.add(vobean);
		});
		return benchmarkUnitVoBeanList;
	}

	public List<BenchamarkSurroundVoBean> findIndicatorBySurround(List<Indicator> indicatorList,Date beginTime,Date endTime,String packageIds) {
		List<String> packageIdList = Arrays.asList(packageIds.split(","));
		//1.根据指标查询detail表
		List<SearchFilter> searchFilters = new ArrayList<>();
		searchFilters.add(SearchFilter.in("indicator", indicatorList));
		searchFilters.add(SearchFilter.in("indicatorPackage.id", packageIdList));
		Specification<IndicatorDetail> detailSpec = JpaSearchUtils.buildAndSpec(searchFilters);
		List<IndicatorDetail> detailList = detailService.findAll(detailSpec);
		
		//2.将指标对应的数据封装到vobean中
		List<BenchamarkSurroundVoBean> vobeanList = new ArrayList<>();
		detailList.forEach(detail ->{
			BenchamarkSurroundVoBean vobean = new BenchamarkSurroundVoBean();
			vobean.setIndicator(detail.getIndicator());
			vobean.setCompanyName(detail.getCompany().getName());
			vobean.setUnitName(detail.getComUnit().getName());
			//查询实际值
			List<SearchFilter> searchs = new ArrayList<>();
			searchs.add(SearchFilter.equal("indicatorDetail.id", detail.getId()));
			searchs.add(SearchFilter.ge("time", beginTime.getTime()));
			searchs.add(SearchFilter.lt("time", endTime.getTime()));
			Specification<IndicatorData> dataSpec = JpaSearchUtils.buildAndSpec(searchs);
			IndicatorData data = dataService.findOne(dataSpec);
			if(data!=null){
				vobean.setData(data.getValue());
			}else {
				vobean.setData(null);
			}
			//查询设计值
			searchs = new ArrayList<>();
			searchs.add(SearchFilter.equal("indicatorDetail.id",  detail.getId()));
			Specification<BenchmarkValue> benchmarkSpec = JpaSearchUtils.buildAndSpec(searchs);
			BenchmarkValue benchmarkValue = benchmarkService.findOne(benchmarkSpec);
			if(benchmarkValue!=null){
				vobean.setDesignValue(benchmarkValue.getDesignValue());
			}else {
				vobean.setDesignValue(null);
			}
			
			//计算同比值
			//查询前一年当前日期的时间并返回数据
			searchs = new ArrayList<>();
			searchs.add(SearchFilter.equal("indicatorDetail.id", detail.getId()));
			searchs.add(SearchFilter.equal("time", endTime.getTime()));
			dataSpec = JpaSearchUtils.buildAndSpec(searchs);
			data = dataService.findOne(dataSpec);
			if(data!=null){
				vobean.setYearOnYearData(data.getValue());
			}else {
				vobean.setYearOnYearData(null);
			}
			
			if(vobean.getData()!=null&&data!=null){
				vobean.setYearOnYearDeviation(vobean.getData() - vobean.getYearOnYearData());
				double yearOnYear = (vobean.getData() - data.getValue())/data.getValue()*100;
				vobean.setYearOnYear(yearOnYear);
			}else {
				vobean.setYearOnYearDeviation(null);
				vobean.setYearOnYear(null);
			}
			
			//计算环比值
			searchs = new ArrayList<>();
			searchs.add(SearchFilter.equal("indicatorDetail.id", detail.getId()));
			searchs.add(SearchFilter.equal("time", endTime.getTime()));
			dataSpec = JpaSearchUtils.buildAndSpec(searchs);
			data = dataService.findOne(dataSpec);
			if(data!=null){
				vobean.setSurroundData(data.getValue());
			}else {
				vobean.setSurroundData(null);
			}
			if(vobean.getData()!=null&&data!=null){
				vobean.setSurroundDeviation(vobean.getData() - vobean.getSurroundData());
				double surround = (vobean.getData() - data.getValue())/data.getValue()*100;
				vobean.setSurround(surround);
			}else {
				vobean.setSurroundDeviation(null);
				vobean.setSurround(null);
			}
			vobeanList.add(vobean);
		});
		return vobeanList;
	}
}
